package com.example.demoapi.api.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demoapi.api.mapper.OrderMapper;
import com.example.demoapi.api.mapper.WalletMapper;
import com.example.demoapi.api.pojo.Orders;
import com.example.demoapi.api.pojo.Result;
import com.example.demoapi.api.pojo.Wallet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Hu
 * @date 2023/2/6
 * @apiNote
 */
@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet> implements WalletService {

    private ReentrantLock lock = new ReentrantLock();

    @Autowired
    private WalletMapper walletMapper;

    @Autowired
    private OrderMapper orderMapper;


    @Override
    public BigDecimal queryUserBalance(int userId) {
        QueryWrapper<Wallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Wallet wallet = walletMapper.selectOne(queryWrapper);
        return wallet.getBalance();
    }


    @Override
    public Result userConsumptionOneHundredYuan(int userId, int orderId) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("user_id", userId);
        int update = 0;
        Orders orders = getUserOrderInformation(orderId);
        lock.lock();
        try {
            BigDecimal nowMoney = queryUserBalance(userId);
            if (nowMoney.compareTo(orders.getOrderAmount()) == -1) {
                return Result.error("余额不足！");
            }
            updateWrapper.set("balance", nowMoney.subtract(orders.getOrderAmount()));
            update = walletMapper.update(null, updateWrapper);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            lock.unlock();
        }
        return update > 0 ?
                Result.success("消费了：" + orders.getOrderAmount() + "元！") :
                Result.error("失败！");
    }

    private Orders getUserOrderInformation(int orderId) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        return orderMapper.selectOne(queryWrapper);
    }

    @Override
    public Result userRefundsTwentyYuan(int userId, int orderId) {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("user_id", userId);
        int update = 0;
        Orders orders = getUserOrderInformation(orderId);
        lock.lock();
        try {
            BigDecimal nowMoney = queryUserBalance(userId);
            updateWrapper.set("balance", orders.getOrderAmount().add(nowMoney));
            update = walletMapper.update(null, updateWrapper);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            lock.unlock();
        }
        return update > 0 ?
                Result.success("退款：" + orders.getOrderAmount() + "元成功！") :
                Result.error("退款失败！");
    }
}
